package com.it.emall.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.it.emall.domain.AdminUser;
import com.it.emall.domain.Comments;
import com.it.emall.domain.Recipes;
import com.it.emall.service.AdminUserService;
import com.it.emall.utils.JwtHelper;
import com.it.emall.utils.Md5;
import com.it.emall.utils.ResponseUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 后台登入认证接口
 */
@RestController
@RequestMapping("/admin")
public class AdminController {

    @Autowired
    private AdminUserService adminUserService;

    @PostMapping("/login")
    public Object login(@RequestBody AdminUser adminUser){//接收参数形式的@RequestBody
        //调用service
        Map<String,Object> json= new HashMap<>();
        AdminUser loginuser = adminUserService.login(adminUser.getUsername());
        System.out.println(loginuser.getPassword());
        String s = Md5.md5(adminUser.getPassword());
        System.out.println(s);
        if(loginuser != null && loginuser.getPassword().equals(s)){
            System.out.println("登入成功");
            Map<String,Object> data = new HashMap<>();
            data.put("token",JwtHelper.createToken(loginuser.getUserId()));
            Map<String,Object> adminInfo = new HashMap<>();
            adminInfo.put("nikeName",loginuser.getUsername());
            adminInfo.put("avatar",loginuser.getAvatar());
            data.put("adminInfo",adminInfo);
            return ResponseUtils.ok(data);
        }else {
            System.out.println("失败");
            return ResponseUtils.fail(ResponseUtils.INVALID_TOKEN,"用户名或者密码错误");
        }

    }


    @GetMapping("/info")
    public Object info(@RequestHeader("token") String token){
        Integer userId = JwtHelper.verifyTokenAndGetUserId(token);
        AdminUser user = adminUserService.selectUserById(userId);
        Map<String,Object> data = new HashMap<>();
        data.put("name",user.getUsername());
        data.put("avatar",user.getAvatar());

        return ResponseUtils.ok(data);


    }


    /**
     * 后台
     */
    // 查询用户列表
    @GetMapping("/manage/userlist")
    public Object getUsers(@RequestParam(value = "page",required = false,defaultValue = "1") Integer page,
                           @RequestParam(value = "limit",required = false,defaultValue = "10") Integer limit) {
        PageHelper.startPage(page,limit);
        List<AdminUser> list = adminUserService.getAllManageUsers();
        PageInfo<AdminUser> pageInfo = new PageInfo<>(list);
        //组织data数据
        Map<String,Object> data = new HashMap<>();

        data.put("list",pageInfo.getList());
        data.put("total",pageInfo.getTotal());
        data.put("pages",pageInfo.getPages());
        data.put("page",pageInfo.getPageNum());
        data.put("limit",pageInfo.getPageSize());
        return ResponseUtils.ok(data);
    }

    // 根据ID删除用户
    @DeleteMapping("/manage/deleteuser")
    public Object deleteUser(@RequestParam Integer userId) {
        int result = adminUserService.deleteManageUserById(userId);
        if (result > 0) {
            return ResponseUtils.ok("删除成功");
        } else {
            return ResponseUtils.fail(ResponseUtils.INVALID_DEFAULT, "删除失败", null);
        }
    }

    // 更新用户信息
    @PutMapping("/manage/updateuser")
    public Object updateUser(@RequestParam Integer userId, @RequestBody AdminUser user) {
        int result = adminUserService.updateManageUser(userId, user);
        if (result > 0) {
            return ResponseUtils.ok("修改成功");
        } else {
            return ResponseUtils.fail(ResponseUtils.INVALID_DEFAULT, "修改失败", null);
        }
    }


    // 搜索用户（带分页）
    @GetMapping("/manage/search")
    public Object searchUsers(
            @RequestParam(value = "username", required = false) String username,
            @RequestParam(value = "email", required = false) String email,
            @RequestParam(value = "age", required = false) Integer age,
            @RequestParam(value = "gender", required = false) String gender,
            @RequestParam(value = "page", required = false, defaultValue = "1") Integer page,
            @RequestParam(value = "limit", required = false, defaultValue = "10") Integer limit
    ) {
        // 启动分页
        PageHelper.startPage(page, limit);

        // 执行条件查询
        List<AdminUser> list = adminUserService.searchManageUsers(username, email, age, gender);

        PageInfo<AdminUser> pageInfo = new PageInfo<>(list);

        // 构建分页响应数据
        Map<String, Object> data = new HashMap<>();
        data.put("list", pageInfo.getList());
        data.put("total", pageInfo.getTotal());
        data.put("pages", pageInfo.getPages());
        data.put("page", pageInfo.getPageNum());
        data.put("limit", pageInfo.getPageSize());

        return ResponseUtils.ok(data);
    }

    /**
     * 根据 userId 查询用户信息
     */
    @GetMapping("/manage/userone")
    public Object getUserById(@RequestParam Integer userId) {
        AdminUser user = adminUserService.getManageUserById(userId);
        if (user != null) {
            return ResponseUtils.ok(user);
        } else {
            return ResponseUtils.fail(ResponseUtils.INVALID_DEFAULT, "查询失败", null);
        }
    }

}
